package model

import (
	"fmt"
	"gorm.io/gorm"
)

type DatabaseDao interface {
	GetCurrentDatabase() (string, error)
	GetAllColumnInfo(where string) (*[]InformationSchemaColumns, error)
}

type defaultDatabaseDao struct {
	engine *gorm.DB
}

func NewDatabaseDao(engine *gorm.DB) *defaultDatabaseDao {
	return &defaultDatabaseDao{
		engine: engine,
	}
}

func (d defaultDatabaseDao) GetCurrentDatabase() (string, error) {
	// 获取指定表信息
	database := ""
	d.engine.Raw("SELECT DATABASE()").Find(&database)
	return database, nil
}

/**
 *  GetAllColumnInfo
 *  @Description: 获取数据库所有的配置信息
 *  @receiver d
 *  @return *[]InformationSchemaColumns
 *  @return error
 */
func (d defaultDatabaseDao) GetAllColumnInfo(where string) (*[]InformationSchemaColumns, error) {
	// 获取指定表信息
	dataColumns := new([]InformationSchemaColumns)
	database, err := d.GetCurrentDatabase()
	fmt.Println(database)
	if nil != err {
		return dataColumns, err
	}
	if where != "" {
		where = " AND " + where
	}
	allColumnInfoSql := "SELECT * FROM information_schema.columns WHERE table_schema = ? " + where + " ORDER BY table_schema ASC,table_name ASC,ordinal_position ASC" + ";"
	find := d.engine.Raw(allColumnInfoSql, database).Find(&dataColumns)
	fmt.Println(find)
	return dataColumns, nil
}
